package org.jeecg.modules.cascv.image.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class TreeUtil {

    public static <T, R> List<T> wrapperTree(List<T> list, Function<? super T, R> id_mapper, Function<? super T, R> pid_mapper, BiConsumer<T, List<T>> setChild, R rootId) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<T> treeList = new LinkedList<>();
        for (T t : list) {
            R _id = id_mapper.apply(t);
            R pid = pid_mapper.apply(t);
            if (ObjectUtils.equals(pid, rootId)) {
                setChild.accept(t, getChild(list, id_mapper, pid_mapper, setChild, _id, 1));
                treeList.add(t);
            }
        }
        return treeList;
    }

    private static <T, R> List<T> getChild(List<T> list, Function<? super T, R> id_mapper, Function<? super T, R> pid_mapper, BiConsumer<T, List<T>> setChild, R pid, int plevel) {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        List<T> childList = new LinkedList<>();
        for (T t : list) {
            R _id = id_mapper.apply(t);
            R _pid = pid_mapper.apply(t);
            if (ObjectUtils.equals(_pid, pid)) {
                setChild.accept(t, getChild(list, id_mapper, pid_mapper, setChild, _id, plevel + 1));
                childList.add(t);
            }
        }
        return childList;
    }
}
